package com.billdowney.qq.robot.plugins.provide;

import cn.hutool.core.io.FileUtil;
import com.billdowney.qq.robot.bean.ConfigBean;
import com.billdowney.qq.robot.enums.RobotEventEnum;
import com.billdowney.qq.robot.plugins.RobotPlugin;
import com.billdowney.qq.robot.plugins.RobotPluginContent;
import com.billdowney.qq.robot.plugins.RobotPluginInfo;
import com.billdowney.qq.robot.util.MessageUtil;
import kotlin.io.FilesKt;
import net.mamoe.mirai.event.events.MemberJoinEvent;
import net.mamoe.mirai.event.events.MemberLeaveEvent;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.BotConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 群管理插件
 *
 * @author BillDowney
 * @date 2021/4/7 20:12
 */
@Component
public class GroupManageRobotPlugin implements RobotPlugin, InitializingBean {
    @Autowired
    private ConfigBean configBean;
    private File welcomeImgDir;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 媒体文件夹
        File baseMediaPath = FilesKt.resolve(BotConfiguration.getDefault().getWorkingDir(), configBean.getWorkspace() + File.separator + "media" + File.separator);
        this.welcomeImgDir = FilesKt.resolve(baseMediaPath, "welcome_img");
        FileUtil.mkdir(this.welcomeImgDir);
    }

    @Override
    public RobotPluginInfo info() {
        return RobotPluginInfo.create("群管理插件", true)
                .addDescLn("自动欢迎入群成员")
                .addDescLn("自动提示退出群成员信息");
    }

    @Override
    public void execute(RobotPluginContent content) {
        if (RobotEventEnum.MEMBER_JOIN.equals(content.getRobotEventEnum())) {
            MemberJoinEvent event = (MemberJoinEvent) content.getEvent();
            MessageChainBuilder builder = MessageUtil.createBuilder();
            builder.append(new At(event.getMember().getId()));
            builder.append(MessageUtil.buildImageMessage(event.getGroup(), MediaRobotPlugin.randomFile(this.welcomeImgDir)));
            content.putReplyMessage(event.getGroup(), builder.build());
        } else if (content.getRobotEventEnum().isMemberLeave()) {
            // 发一条消息到群里
            MemberLeaveEvent event = content.getMemberLeaveEvent();
            // 构建链式消息
            MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
            configBean.getRootManageQq().forEach(item -> {
                At at = new At(item);
                messageChainBuilder.append(at);
            });
            messageChainBuilder.append(String.format("\n有人离开了：%s(%s)", event.getMember().getNick(), event.getMember().getId()));
            content.putReplyMessage(event.getGroup(), messageChainBuilder);
        }
    }
}
